﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Myapplication
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var see = Session["Username"];

            if(see == null)
            {
                Response.Redirect("Login.aspx");
            }

            if (!IsPostBack)
            {
                FillData();
            }
        }
        private void FillData()
        {
            var sql = string.Format("select * from Task");

            var dt = Dbhelper.GetDatatable(sql);

            GridView1.DataSource = dt;

            GridView1.DataBind();
        }
        private string GetVal(int rowIndex, int colIndex)
        {
            var control = GridView1.Rows[rowIndex].Cells[colIndex];
            var res = control.Controls.Count > 0 ? ((TextBox)control.Controls[0]).Text : control.Text;
            return res;
        }
        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView1.PageIndex = e.NewPageIndex;
            FillData();
        }

        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            var id = GetVal(e.RowIndex, 0);

            var sql = string.Format("delete from Task where id = {0}",id);

            Dbhelper.ExeOperation(sql);

            FillData();


        }

        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            var id = GetVal(e.NewEditIndex, 0);

            Response.Redirect("TaskEdit.aspx?id=" + id);

        }

        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if(e.CommandName == "detail")
            {
                int index = Convert.ToInt32(e.CommandArgument);

                int id = Convert.ToInt32(GetVal(index, 0));

                Response.Redirect("TaskDetail.aspx?id="+id);
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            Response.Redirect("TaskEdit.aspx");
        }

        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {

        }
    }
}